import constant from './constant'

// 存储变量名
let storageKey = 'storage_data'

// 存储节点变量名
let storageNodeKeys = [constant.avatar, constant.name, constant.roles, constant.permissions]

const storage = {
  set: function (key: string, value: string) {
    if (storageNodeKeys.indexOf(key) != -1) {
      let tmp = uni.getStorageSync(storageKey)
      tmp = tmp ? tmp : {}
      tmp[key] = value
      uni.setStorageSync(storageKey, tmp)
    }
  },
  get: function (key: string) {
    let storageData = uni.getStorageSync(storageKey) || {}
    return storageData[key] || ""
  },
  remove: function (key: string) {
    let storageData = uni.getStorageSync(storageKey) || {}
    delete storageData[key]
    uni.setStorageSync(storageKey, storageData)
  },
  clean: function () {
    uni.removeStorageSync(storageKey)
  }
}

/**
 * 安全地获取存储数据 - 解决 APP 端和小程序端差异
 * @param key 存储键
 * @param defaultValue 默认值
 * @returns 存储的值或默认值
 */
export function getStorageSync(key: string, defaultValue: any = null): any {
  try {
    const value = uni.getStorageSync(key);

    // 处理各种无效值的情况
    if (value === null || value === undefined || value === '') {
      console.log(`存储数据为无效值 [${key}]:`, value);
      return defaultValue;
    }

    return value;
  } catch (error) {
    console.error(`获取存储数据失败 [${key}]:`, error);
    return defaultValue;
  }
}

/**
 * 安全地设置存储数据
 * @param key 存储键
 * @param value 存储值
 * @returns 是否成功
 */
export function setStorageSync(key: string, value: any): boolean {
  try {
    // 确保值不为 null 或 undefined
    if (value === null || value === undefined) {
      uni.removeStorageSync(key);
      return true;
    }

    uni.setStorageSync(key, value);
    return true;
  } catch (error) {
    console.error(`设置存储数据失败 [${key}]:`, error);
    return false;
  }
}

/**
 * 获取登录相关的存储数据
 * @returns 登录数据对象
 */
export function getLoginStorageData() {
  return {
    username: getStorageSync('username', ''),
    password: getStorageSync('password', ''),
    rememberMe: getStorageSync('rememberMe', 'false')
  };
}

/**
 * 设置登录相关的存储数据
 * @param data 登录数据
 * @returns 是否全部设置成功
 */
export function setLoginStorageData(data: {
  username?: string;
  password?: string;
  rememberMe?: boolean;
}) {
  const results = [
    setStorageSync('username', data.username || ''),
    setStorageSync('password', data.password || ''),
    setStorageSync('rememberMe', String(data.rememberMe || false))
  ];

  return results.every(result => result);
}

/**
 * 清除登录相关的存储数据
 * @returns 是否全部清除成功
 */
export function clearLoginStorageData() {
  const results = [
    uni.removeStorageSync('username'),
    uni.removeStorageSync('password'),
    uni.removeStorageSync('rememberMe')
  ];

  return true; // 移除操作通常不会失败
}

export default storage
